class PromiseD {
  constructor(executor) {
    this.state = 'pending';
    this.callback = [];
    this.value = '';
    this.reason = '';
    executor(this._resolve.bind(this));
  }
  then(onFulled) {
    return new PromiseD(resolve => {
      this._handle({
        onFullfilled: onFulled || null,
        resolve
      })
    })
  }
  _resolve(value) {
    // 如果value值是一个promise，则它的state切换依赖于当前promise的state切换
    if(value instanceof PromiseD) {
      return value.then.call(value, this._resolve.bind(this));
    }
    this.value = value;
    this.state = 'fullfilled';
    // 触发回调函数执行
    this.callback.forEach(fn => this._handle(fn));
  }
  _handle(callback) {
    // 判断当前promise的状态
    if(this.state === 'pending') {
      return this.callback.push(callback);
    }
    if(this.state === 'fullfilled') {
      // 判断callback中指定的类型
      if(!callback.onFullfilled) {
        return callback.resolve(this.value);
      }
      let ret = callback.onFullfilled(this.value);
      return callback.resolve(ret);
    }
  }
}

let pro = new PromiseD(function(resolve) {
  setTimeout(function() {
    resolve(90)
  }, 1000)
}).then(function(r1) {
  console.log(r1);
  return new PromiseD(resolve => {
    console.log('r1 返回的 resolve被执行了');
    setTimeout(resolve, 1200, 'r1 的resolve 结果返回')
  }).then(r3 => {
    console.log('r3', r3);
    return 10
  });
}).then(function(r2) {
  console.log(r2);
  return r2 + ' r2';
})